import Vue from 'vue'
import Vuex from 'vuex'
import { CALLBACK, SEARCH_NOVEL, STOP_SEARCH_NOVEL, UPDATE_NOVEL, CACHE_CHAPTER_LIST, GEN_MOBI } from '../api/channel'
import { status } from '@/api/constant'

// import { createPersistedState, createSharedMutations } from 'vuex-electron'

import modules from './modules'

Vue.use(Vuex)

export default new Vuex.Store({
  modules,
  state: {
    socket: {
      isConnected: false,
      message: '',
      reconnectError: false,
    },
    searchList: [],
    chapterList: {},
    chapterListLoading: false
  },
  mutations:{
    SOCKET_ONOPEN (state, event)  {
      Vue.prototype.$socket = event.currentTarget
      state.socket.isConnected = true
    },
    SOCKET_ONCLOSE (state, event)  {
      state.socket.isConnected = false
    },
    SOCKET_ONERROR (state, event)  {
      console.error(state, event)
    },
    // default handler called for all methods
    SOCKET_ONMESSAGE (state, message)  {
      switch(message.type) {
        case SEARCH_NOVEL + CALLBACK: 
          if(message.payload.code === 200){
            state.searchList.push(...message.payload.data)
          }
          break
        case STOP_SEARCH_NOVEL + CALLBACK: 
          Vue.prototype.$message.success("操作成功")
          break
        case CACHE_CHAPTER_LIST + CALLBACK:
          if(message.payload.code === 200){
            const data = message.payload.data
              if (data.status === 'done') {
                Vue.prototype.$message.success('全部缓存完毕')
                state.chapterListLoading = false
              } else if (data.status === 'item-done'){
                Vue.set(state.chapterList, data.item.chapterUrl, status[0])
              }
          }
          break
        case GEN_MOBI + CALLBACK:
          if(message.payload.code === 200){
            const data = message.payload.data
            if(data === 'pending') {
              console.log(message.payload.message)
            } else {
              Vue.prototype.$message.success('生成完毕')
            }
          } else {
            Vue.prototype.$message.error(message.payload.message)
          }
      }
    },
    // mutations for reconnect methods
    SOCKET_RECONNECT(state, count) {
      console.info(state, count)
    },
    SOCKET_RECONNECT_ERROR(state) {
      state.socket.reconnectError = true;
    },
    SAVE_SEARCH_LIST(state, list) {
      state.searchList = list
    },
    SAVE_CHAPTER_LIST(state, list) {
      state.chapterList = list
      state.chapterListLoading = true
    },
  },
  // plugins: [
  //   createPersistedState(),
  //   createSharedMutations()
  // ],
  strict: process.env.NODE_ENV !== 'production'
})
